package cn.school.mybatis.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	private static String resource = "mybatis-config.xml";
	private static SqlSessionFactory sqlSessionFactory = null;
	// private static SqlSessionFactory sqlSessionFactory = null;

	static {
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream(resource);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 构建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	}

	public static SqlSession getSqlSession() {
		// 1、读取核心的配置文件
//		InputStream inputStream = null;
//		try {
//			inputStream = Resources.getResourceAsStream(resource);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		// 构建SqlSessionFactory
//		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		// 打开链接
		return sqlSessionFactory.openSession();
	}

//	public static SqlSession getSqlSession() {
//		return sqlSessionFactory.openSession();
//	}

	// 释放资源
	public static void close(SqlSession session) {
		if (session != null) {
			session.close();
		}

	}

}
